var vm = new Vue({
	el: '#app',
	data: function() {
		return {
			searchUser: {},
			page: {
				index: 1,
				total: 0,
				currentPage: 1,
				pageSize: 10,
			},
			users: [],
			dialogAddVisible: false,
			dialogEditVisible: false,
			dialogRoleVisible: false,
			editUser: {
				username: '',
				nickname: '',
				mobile: '',
				email: ''
			},
			addUser: {
				username: '',
				nickname: ''
			},
			roleData: [],
			hasRole: [],
			roles: [],

			// 表单校验规则开始
			editRules: {
				nickname: [{
						required: true,
						message: '请输入昵称',
						trigger: 'blur'
					},
					{
						min: 2,
						max: 20,
						message: '长度在 2到 20个字符',
						trigger: 'blur'
					},
					{
						validator: function(rule, value, callback) {
							if(!isNickname(value)) {
								callback(new Error('昵称由中文数字字母或下划线组成'));
							} else {
								callback();
							}
						},
						trigger: 'blur'
					}
				],
				mobile: [{
					validator: function(rule, value, callback) {
						if(!isMobile(value) && value != null && value != '') {
							callback(new Error('请输入正确的手机号'));
						} else {
							callback();
						}
					},
					trigger: 'blur'
				}],
				email: [{
					validator: function(rule, value, callback) {
						if(!isEmail(value) && value != null && value != '') {
							callback(new Error('邮箱格式不正确'));
						} else {
							callback();
						}
					},
					trigger: 'blur'
				}]
			},
			addRules: {
				username: [{
						required: true,
						message: '请输入用户名',
						trigger: 'blur'
					},
					{
						min: 2,
						max: 20,
						message: '长度在 2到 20个字符',
						trigger: 'blur'
					},
					{
						validator: function(rule, value, callback) {
							if(!isUsername(value)) {
								callback(new Error('用户名由中文数字字母或下划线组成'));
								return;
							}
							axios({
								method: 'get',
								url: CONST_URL + '/user/checkUser',
								params: {
									username: value
								}
							}).then(function(response) {
								if(response.data.code == '0000') {
									if(response.data.data) {
										callback(new Error('用户已存在'));
									} else {
										callback();
									}
								} else {
									console.log(response.data);
								}
							}).catch(function(error) {
								alert(error.response.status);
								console.log(error);
							});
						},
						trigger: 'blur'
					}
				],
				nickname: [{
						required: true,
						message: '请输入昵称',
						trigger: 'blur'
					},
					{
						min: 2,
						max: 20,
						message: '长度在 2到 20个字符',
						trigger: 'blur'
					},
					{
						validator: function(rule, value, callback) {
							if(!isNickname(value)) {
								callback(new Error('昵称由中文数字字母或下划线组成'));
							} else {
								callback();
							}
						},
						trigger: 'blur'
					}
				]
			}
			// 表单校验规则结束
		};
	},
	methods: {
		/**
		 * 查询该页数的数据
		 * 
		 * @param val 当前页数
		 */
		search: function(val) {
			var _this = this;
			authAxios({
				method: 'get',
				url: CONST_URL + '/user/findAll',
				params: {
					page: val - 1,
					size: _this.page.pageSize
				}
			}).then(function(response) {
				if(response.data.code == '0000') {
					var pageUser = response.data.data;
					_this.page.index = (val - 1) * _this.page.pageSize + 1;
					_this.users = pageUser.content;
					_this.page.total = pageUser.totalElements;
				} else {
					_this.$message.error('加载数据失败！');
					console.log(response.data);
				}
			}).catch(function(error) {
				alert(error.response.status);
				console.log(error);
			});
		},
		/**
		 * 删除用户
		 * 
		 * @param user 用户
		 */
		deleteUser: function(user) {
			var _this = this;
			this.$confirm('确认删除用户“' + user.nickname + '(' + user.username + ')' + '”吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function() {
				authAxios({
					method: 'post',
					url: CONST_URL + '/user/delete',
					params: user
				}).then(function(response) {
					if(response.data.code == '0000') {
						_this.search(_this.page.currentPage);
						_this.$message.success('删除成功！');
					} else {
						_this.$message.error('删除失败！');
						console.log(response.data);
					}
				}).catch(function(error) {
					alert(error.response.status);
					console.log(error);
				});
			}).catch(function() {
				_this.$message({
					type: 'info',
					message: '已取消删除'
				});
			});
		},
		edit: function(user) {
			this.dialogEditVisible = true;
			this.editUser = JSON.parse(JSON.stringify(user));
		},
		/**
		 * 重置用户密码
		 * 
		 * @param user 用户
		 */
		resetPassword: function(user) {
			var _this = this;
			this.$confirm('确认重置用户“' + user.nickname + '(' + user.username + ')' + '”的密码吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function() {
				authAxios({
					method: 'post',
					url: CONST_URL + '/user/resetPassword',
					params: user
				}).then(function(response) {
					if(response.data.code == '0000') {
						_this.search(_this.page.currentPage);
						_this.$message.success('重置成功！');
					} else {
						_this.$message.error('重置失败！');
						console.log(response.data);
					}
				}).catch(function(error) {
					alert(error.response.status);
					console.log(error);
				});
			}).catch(function() {
				_this.$message({
					type: 'info',
					message: '已取消重置'
				});
			});
		},
		/**
		 * 修改用户
		 */
		submitEditForm: function(formName) {
			var _this = this;
			if(_this.editUser.mobile == '') {
				_this.editUser.mobile = null;
			}
			if(_this.editUser.email == '') {
				_this.editUser.email = null;
			}
			this.$refs[formName].validate(function(valid) {
				if(!valid) {
					console.log('error submit!!');
					return false;
				}
				axios({
					method: 'post',
					url: CONST_URL + '/user/update',
					data: {
						id: _this.editUser.id,
						nickname: _this.editUser.nickname,
						mobile: _this.editUser.mobile,
						email: _this.editUser.email,
					}
				}).then(function(response) {
					if(response.data.code == '0000') {
						_this.dialogRegVisible = false;
						_this.$message.success('修改成功！');
					} else {
						_this.$message.error('修改失败！');
						console.log(response.data);
					}
				}).catch(function(error) {
					alert(error.response.status);
					console.log(error);
				});
			});
		},
		/**
		 * 新增用户
		 */
		submitAddForm: function(formName) {
			var _this = this;
			this.$refs[formName].validate(function(valid) {
				if(!valid) {
					console.log('error submit!!');
					return false;
				}
				axios({
					method: 'post',
					url: CONST_URL + '/user/add',
					data: _this.addUser
				}).then(function(response) {
					if(response.data.code == '0000') {
						_this.search(_this.page.currentPage);
						_this.dialogAddVisible = false;
						_this.$message.success('新增成功！');
					} else {
						_this.$message.error('新增失败！');
						console.log(response.data);
					}
				}).catch(function(error) {
					alert(error.response.status);
					console.log(error);
				});
			});
		},
		/**
		 * 编辑用户角色
		 */
		editRole: function(user) {
			var _this = this;
			_this.editUser = JSON.parse(JSON.stringify(user));
			_this.dialogRoleVisible = true;
			return authAxios({
				method: 'get',
				url: CONST_URL + '/user/findRole',
				params: {
					userId: _this.editUser.id
				}
			}).then(function(response) {
				_this.hasRole = [];
				if(response.data.code == '0000') {
					for(var i = 0; i < response.data.data.length; i++) {
						_this.hasRole.push(response.data.data[i].id);
					}
				} else {
					_this.$message.error('加载数据失败！');
					console.log(response.data);
				}
			}).catch(function(error) {
				alert(error.response.status);
				console.log(error);
			});
		},
		/**
		 * 保存用户角色
		 */
		saveRole: function() {
			var _this = this;
			this.$confirm('确认保存对“' + _this.editUser.nickname + '(' + _this.editUser.username + ')' + '”的修改吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(function() {
				authAxios({
					method: 'post',
					url: CONST_URL + '/user/updateUserRole',
					data: {
						userId: _this.editUser.id,
						roleIds: _this.hasRole
					}
				}).then(function(response) {
					if(response.data.code == '0000') {
						_this.$message.success('修改成功！');
					} else {
						_this.$message.error('修改用户角色失败！');
						console.log(response.data);
					}
				}).catch(function(error) {
					alert(error.response.status);
					console.log(error);
				});
			}).catch(function() {
				_this.$message({
					type: 'info',
					message: '已取消保存'
				});
			});
		},
		/**
		 * 查询所有权限信息
		 */
		findAllRole: function() {
			var _this = this;
			return authAxios({
				method: 'get',
				url: CONST_URL + '/role/all'
			}).then(function(response) {
				if(response.data.code == '0000') {
					_this.roles = response.data.data;
					_this.roleData = [];
					for(var i = 0; i < _this.roles.length; i++) {
						_this.roleData.push({
							key: _this.roles[i].id,
							label: _this.roles[i].description
						});
					}
				} else {
					_this.$message.error('加载数据失败！');
					console.log(response.data);
				}
			}).catch(function(error) {
				alert(error.response.status);
				console.log(error);
			});
		}
	},
	mounted: function() {
		this.$nextTick(function() {
			var _this = this;
			checkToken().then(function() {
				var token = localStorage.getItem('token');
				if(token != null) {
					token = JSON.parse(token);
					authAxios.defaults.headers.common['Authorization'] = token.token_type + ' ' + token.access_token;
				}
			}).then(function() {
				_this.search(1);
				_this.findAllRole();
			});
		});
	}
});